<template>
	<view class="settlement-container">
		<!-- 地址选择卡片 -->
		<view class="settlement-container2">
			<view class="card address-card" @click="selectAddress">
				<view class="card-header">
					<text>配送地址:</text>
				</view>
				<view class="card-content">
					<text>{{ selectedAddress ? (selectedAddress.name + '（' + selectedAddress.phone + '）') : '' }}</text>
					<text>{{ selectedAddress ? (selectedAddress.address_line1 + ' ' + selectedAddress.address_line2) : '请选择地址' }}</text>
				</view>
			</view>

			<!-- 商品信息卡片 -->
			<view class="card">
				<view class="card-header">
					<text>商品信息</text>
				</view>
				<view class="card-content">
					<view v-for="(item, index) in cartItems" :key="index" class="product-item">
						<image :src="item.img" class="product-image"></image>
						<view class="product-info">
							<text class="product-name">{{ item.name }}</text>
							<view class="product-price-quantity">
								<text
									class="product-price">￥{{ formatPrice((item.discount_price || item.original_price) * item.quantity) }}</text>
								<text class="product-quantity">x{{ item.quantity }}</text>
							</view>
						</view>
					</view>
					<!-- 会员折扣 -->
					<view class="membership-discount" v-if="membershipDiscount > 0">
						<text>会员折扣:</text>
						<text class="discount-value">{{ membershipDiscount }}折</text>
					</view>
					<view class="membership-discount">
						<text>运费:</text>
						<text class="discount-value">￥{{ formatPrice(shippingCost) }}</text>
					</view>
				</view>
			</view>

			<!-- 运费和留言卡片 -->
			<view class="card">
				<view class="card-header">
					<text>留言:</text>
				</view>
				<view class="card-content">
					<input v-model="message" type="text" placeholder="请输入留言（最多30字）" maxlength="30" />
				</view>
<!-- 				<view class="card-footer">
					<view class="shipping-cost">
						<text>运费:</text>
						<text class="cost-value">￥{{ formatPrice(shippingCost) }}</text>
					</view>
				</view> -->
			</view>
		</view>

		<!-- 合计和提交订单固定条 -->
		<view class="total-section">
			<view class="total-amount">
				<text>合计:</text>
				<text class="amount-value">￥{{ formatPrice(totalAmount) }}</text>
			</view>
			<view class="submit-order">
				<button @click="showPaymentMethods">提交订单</button>
			</view>
		</view>

		<!-- 支付方式弹窗 -->
		<view class="payment-methods" v-if="showPaymentMethodsDialog" @click="closePaymentMethodsDialog">
			<view class="payment-methods-content" @click.stop>
				<button @click="payWithWechat" class="payment-button">微信支付</button>
				<button @click="payWithAlipay" class="payment-button">支付宝支付</button>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			selectedAddress: null,
			cartItems: [],
			shippingCost: 0,
			message: '',
			totalAmount: 0,
			showPaymentMethodsDialog: false,
			membershipDiscount: 0, // 新增会员折扣
		};
	},
	methods: {
		selectAddress() {
			uni.navigateTo({
				url: '/pages/address/address'
			});
		},
		goSuccess() {
			uni.navigateTo({
				url: '/pages/success/success'
			});
		},
		fetchCartItems() {
			const token = uni.getStorageSync('Authorization');
			const url = 'http://localhost:8887/Shoppingcart/selectcheck';
			const header = {
				'Authorization': token
			};
			uni.request({
				url,
				method: 'GET',
				header,
				success: (res) => {
					if (res.data.success) {
						this.cartItems = res.data.data;
						this.calculateTotal();
						this.fetchUserInfo(token); // 获取用户信息
					} else {
						uni.showToast({
							title: '获取商品信息失败',
							icon: 'none'
						});
					}
				},
				fail: () => {
					uni.showToast({
						title: '请求失败',
						icon: 'none'
					});
				}
			});
		},
		fetchUserInfo(token) {
			const url = 'http://localhost:8887/user/userInfo';
			const header = {
				'Authorization': token
			};
			uni.request({
				url,
				method: 'GET',
				header,
				success: (res) => {
					if (res.data.code === 200 && res.data.success) {
						this.membershipDiscount = parseFloat(res.data.data.discount); // 存储会员折扣
						this.calculateTotal(); // 重新计算总价
					}
				},
				fail: () => {
					uni.showToast({
						title: '获取用户信息失败',
						icon: 'none'
					});
				}
			});
		},
		calculateTotal() {
			let total = this.cartItems.reduce((sum, item) => {
				const price = parseFloat(item.discount_price || item.original_price);
				return sum + (price * parseInt(item.quantity, 10));
			}, this.shippingCost);
			// 应用会员折扣
			total = total * (this.membershipDiscount / 100);
			this.totalAmount = parseFloat(total).toFixed(2);
		},
		formatPrice(value) {
			return parseFloat(value).toFixed(2);
		},
		showPaymentMethods() {
			this.showPaymentMethodsDialog = true;
		},
		closePaymentMethodsDialog() {
			this.showPaymentMethodsDialog = false;
		},
		payWithWechat() {
			this.processPayment('微信支付');
		},
		payWithAlipay() {
			this.processPayment('支付宝支付');
		},
		processPayment(paymentMethod) {
		    const token = uni.getStorageSync('Authorization');
		    const url = 'http://localhost:8887/Order/add';
		    const orderData = {
		        useraddress_id: this.selectedAddress.id,
		        total_amount: this.totalAmount,
		        payment_method: paymentMethod,
		        message: this.message,
		        orderProducts: this.cartItems.map(item => ({
		            product_id: item.product_id,
		            quantity: item.quantity,
		            discount_price: item.discount_price,
		            original_price: item.original_price
		        }))
		    };
		    const header = {
		        'Authorization': token,
		        'Content-Type': 'application/json'
		    };
		    uni.request({
		        url,
		        method: 'POST',
		        header,
		        data: orderData,
		        success: (res) => {
		            if (res.data.success) {
		                uni.showToast({
		                    title: '支付成功',
		                    icon: 'success'
		                });
		                console.log(res.data.data); // 打印返回的订单数据
		                const orderId = res.data.data.id; // 假设返回的数据中包含 orderId
		                this.goToOrderDetails(orderId); // 跳转到订单详情页面
		            } else {
		                uni.showToast({
		                    title: '支付失败',
		                    icon: 'none'
		                });
		                this.closePaymentMethodsDialog();
		            }
		        },
		        fail: () => {
		            uni.showToast({
		                title: '请求失败',
		                icon: 'none'
		            });
		            this.closePaymentMethodsDialog();
		            this.goSuccess(); // 请求失败时跳转到 success 页面
		        }
		    });
		},
		goToOrderDetails(orderId) {
		        uni.navigateTo({
		            url: `/pages/orderdetails/orderdetails?id=${orderId}`
		        });
		    },
		fetchUserDefaultAddress() {
			const token = uni.getStorageSync('Authorization');
			const url = 'http://localhost:8887/Useraddress/selectuser_id';
			const header = {
				'Authorization': token
			};
			uni.request({
				url,
				method: 'GET',
				header,
				success: (res) => {
					if (res.data.success) {
						this.selectedAddress = res.data.data[0] || null;
					}
				},
				fail: () => {
					uni.showToast({
						title: '获取地址信息失败',
						icon: 'none'
					});
				}
			});
		},
		fetchSelectedAddress() {
			const selectedAddressId = uni.getStorageSync('selectedAddressId');
			if (selectedAddressId) {
				const token = uni.getStorageSync('Authorization');
				const url = `http://localhost:8887/Useraddress/select?id=${selectedAddressId}`;
				const header = {
					'Authorization': token,
				};
				uni.request({
					url,
					method: 'GET',
					header,
					success: (res) => {
						if (res.data.success) {
							this.selectedAddress = res.data.data;
						} else {
							uni.showToast({
								title: '获取地址信息失败',
								icon: 'none',
							});
						}
					},
					fail: () => {
						uni.showToast({
							title: '请求失败',
							icon: 'none',
						});
					},
				});
			}
		}
	}, // 确保这里是逗号
	onShow() {
		this.fetchCartItems();
		this.fetchSelectedAddress();
	}
}
</script>

<style>
	.settlement-container {
		position: relative;
		padding: 15px;
	}

	.settlement-container2 {
		padding-bottom: 200px;
		/* 留出空间给底部支付栏 */
	}

	.card {
		background-color: #f9f9f9;
border: 1px solid #eaeaea;
margin-bottom: 20rpx;
padding: 20rpx;
box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.card-header {
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.card-content {
	font-size: 28rpx;
	color: #555;
	display: flex;
	flex-direction: column;
}

.address-card .card-content {
	flex-direction: column;
}

.product-item {
	display: flex;
	align-items: center;
	margin-bottom: 10px;
}

.product-image {
	width: 60px;
	height: 60px;
	margin-right: 10px;
}

.product-info {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.product-name {
	font-size: 28rpx;
	color: #333;
	white-space: normal;
	word-break: break-word;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
}

.product-price-quantity {
	display: flex;
	justify-content: space-between;
}

.product-price {
	color: #ff9966;
	font-size: 30rpx;
}

.product-quantity {
	font-size: 24rpx;
	color: #888;
}

.card-footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-top: 20rpx;
}

.shipping-cost {
	font-size: 28rpx;
	color: #555;
}

.cost-value {
	font-size: 30rpx;
	color: #ff9966;
}

.buyer-message input {
	border: 1px solid #eee;
	padding: 10px;
	border-radius: 4px;
	width: 100%;
	font-size: 28rpx;
}

.total-section {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: white;
	padding: 20rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
	display: flex;
	justify-content: space-between;
	align-items: center;
	z-index: 1000;
	/* 确保在弹窗之上 */
}

.total-amount {
	font-size: 32rpx;
	color: #333;
}

.amount-value {
	font-size: 36rpx;
	color: #ff9966;
}

.submit-order button {
	background-color: #ff9966;
	color: white;
	border: none;
	padding: 10px;
	width: 100%;
}

.payment-methods {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	top: 0;
	background-color: rgba(0, 0, 0, 0.6);
	display: flex;
	justify-content: flex-end;
	align-items: flex-end;
	/* 使弹窗内容在底部 */
	z-index: 1001;
	/* 确保弹窗在底部按钮之上 */
}

.payment-methods-content {
	display: flex;
	flex-direction: row;
	justify-content: center;
	background-color: white;
	padding: 10px;
	width: 100%;
	box-sizing: border-box;
	/* margin-bottom: 20px; */
	/* 距离底部的距离 */
	border-top: 1px solid #eee;
	/* 去除圆角，添加边框 */
}

.payment-methods-content .payment-button {
	flex: 1;
	height: 80rpx;
	background-color: #ff9966;
	color: white;
	border: none;
	font-size: 28rpx;
	margin: 0 10px;
	border-top: 1px solid #eee;
	/* 分割线 */
}

/* 新增会员折扣样式 */
.membership-discount {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-top: 10px;
	font-size: 28rpx;
	color: #555;
}

.discount-value {
	color: #ff9966;
	font-size: 30rpx;
}
</style>